var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//引用session模块
var session = require('express-session');
var router = require('./routes/index');
//var index = require('./routes/index');
//var users = require('./routes/users');
//引入ejs模块
var ejs = require('ejs');

//加载ueditor 模块  
var ueditor = require("ueditor");

//加载时间格式化模块
var moment = require('moment');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', ejs.__express); //增加
app.set('view engine', 'html'); //修改

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
	extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({
	secret: 'admin',
	resave: true,
	saveUninitialized: true
}));

app.use("/ueditor/ue", ueditor(path.join(__dirname, 'public'), function(req, res, next) {
	// ueditor 客户发起上传图片请求  
	var ActionType = req.query.action; 
	if (ActionType === 'uploadimage' || ActionType === 'uploadfile' || ActionType === 'uploadvideo') { 
		var foo = req.ueditor;
		//图片请求地址
		//路径格式{yyyy}-{mm}-{dd}_{rand:6}_{filename}
		//设置时间目录console.log(moment(new Date).format("YYYY-MM-DD HH:mm:ss"));
		var datedir=moment(new Date).format("YYYY_MM_DD");
		var file_url = '/upload/ueditor/img/'+datedir+'/';

		var imgname = req.ueditor.filename;
		
		/*其他上传格式的地址*/  
        if (ActionType === 'uploadfile') {  
            file_url = '/upload/ueditor/file/'+datedir+'/'; //附件  
        }  
        if (ActionType === 'uploadvideo') {  
            file_url = '/upload/ueditor/video/'+datedir+'/'; //视频  
        }  

		
		res.ue_up(file_url); //你只要输入要保存的地址 。保存操作交给ueditor来做  
		res.setHeader('Content-Type', 'text/html'); //IE8下载需要设置返回头尾text/html 不然json返回文件会被直接下载打开  
	}
	//  客户端发起图片列表请求  
	else if(req.query.action === 'listimage') {
		//目前此版本不支持对目录管理
		var dir_url = '/upload/ueditor/img/';
		res.ue_list(dir_url); // 客户端会列出 dir_url 目录下的所有图片  
	}
	// 客户端发起其它请求  
	else {
		// console.log('config.json')  
		res.setHeader('Content-Type', 'application/json');
		res.redirect('/ueditor/jsp/config.json');
	}
}));

router(app);
//app.use('/', index);
//app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
	var err = new Error('Not Found');
	err.status = 404;
	next(err);
});

// error handler
app.use(function(err, req, res, next) {
	// set locals, only providing error in development
	res.locals.message = err.message;
	res.locals.error = req.app.get('env') === 'development' ? err : {};

	// render the error page
	res.status(err.status || 500);
	res.render('error', {
		err: err
	});
});

module.exports = app;